package top.jybill.factory;

import top.jybill.service.IAccountService;
import top.jybill.utils.ThreadManager;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ServiceFactory {
  private IAccountService accountService;
  private ThreadManager threadManager;

  public void setThreadManager(ThreadManager threadManager) {
    this.threadManager = threadManager;
  }

  public void setAccountService(IAccountService accountService) {
    this.accountService = accountService;
  }

  /**
   * 动态代理获取service代理实例
   *
   * @return
   */
  public IAccountService getAccountService() {
    return (IAccountService) Proxy.newProxyInstance(accountService.getClass().getClassLoader(),
            accountService.getClass().getInterfaces(),
            new InvocationHandler() {
              @Override
              public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                try {
                  method.invoke(accountService, args);
                  threadManager.commit(); // 提交后conn会自动close()
                } catch (Exception e) {
                  threadManager.rollback(); // 异常回滚
                  e.printStackTrace();
                }
                return null;
              }
            });
  }


}
